<template>
  <div class="upload">
    <div @click="visible = true">
      <slot>
        <a-button type="primary">
          <template #icon>
            <icon-upload />
          </template>
          上传文件
        </a-button>
      </slot>
    </div>

    <a-modal
      v-model:visible="visible"
      title="上传文件"
      :close-on-click-modal="false"
      width="500px"
      :modal="false"
      @ok="handleClose"
      @on-before-close="handleClose"
    >
      <div style="height: 400px;overflow-x: hidden; overflow-y: auto;">
        <a-upload
          ref="uploadRefs"
          v-model:file-list="fileList"
          multiple
          :action="actionURL"
          :limit="limit"
          :headers="headers"
          :data="data"
          :accept="getAccept"
          @success="handleSuccess"
          @exceed-limit="handleExceed"
          @error="handleError"
        >
          <template #upload-button>
            <div
              style="
                width: 460px;
                height: 120px;
                color: var(--color-text-1);
                line-height: 128px;
                text-align: center;
                background-color: var(--color-fill-2);
                border: 1px dashed var(--color-fill-4);
                border-radius: 2;"
            >
              <div>
                将文件拖动到此处 或
                <span style="color: #3370FF"> 单击上载</span>
              </div>
            </div>
          </template>
        </a-upload>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import {computed, ref, shallowRef, toRaw, defineEmits, defineProps} from 'vue'
// import useUserStore from '@/store/modules/user'
import {Message} from "@arco-design/web-vue";
import { getToken } from "@/utils/auth";

const emits = defineEmits(['ok'])

const props = defineProps({
  // 上传文件类型
  type: {
    type: String,
    default: 'image'
  },
  // 是否支持多选
  multiple: {
    type: Boolean,
    default: true
  },
  // 多选时最多选择几条
  limit: {
    type: Number,
    default: 10
  },
  // 上传时的额外参数
  data: {
    type: Object,
    default: () => ({})
  },
})

const fileList = ref([])
// const userStore = useUserStore()
const uploadRefs = shallowRef()
const hasSuccess = ref(false)

const BASE_URL = import.meta.env.VITE_API_BASE_URL
const actionURL = ref(`${BASE_URL}/admin/upload/multiple`)

// const headers = computed(() => ({
//   token: userStore.token
// }))

const headers = ref({ Authorization: `Bearer ${getToken()}` });

const visible = ref(false)

const handleSuccess = (fileItem) => {
  hasSuccess.value = true
  console.log(fileItem)
  // const allSuccess = fileLists.every((item) => item.status === 'success')
  // if (allSuccess) {
  //   uploadRefs.value?.clearFiles()
  //   visible.value = false
  // }
  // emits('change', file)
  // if (response.code === 200) {
  //   emits('success', response)
  // }
}

const handleError = (event: any, file: any) => {
  Message.error(`${file.name}文件上传失败`)
  uploadRefs.value?.abort(file)
}
const handleExceed = () => {
  Message.error(`超出上传上限${props.limit}，请重新上传`)
}
const handleClose = () => {
  console.log(fileList.value);
  // 判断是否全部上传
  let isFinish = true
  fileList.value.forEach(item => {
    if (item.status !== 'done') {
      isFinish = false
    }
  })
  if (!isFinish) {
    Message.warning('文件未完成上传')
  }

  return false

  // visible.value = false
  // if (hasSuccess.value) {
  //   emits('ok')
  // }
}

const getAccept = computed(() => {
  switch (props.type) {
    case 'image':
      return '.jpg,.png,.gif,.jpeg'
    case 'video':
      return '.wmv,.avi,.mpg,.mpeg,.3gp,.mov,.mp4,.flv,.rmvb,.mkv'
    default:
      return '*'
  }
})

</script>

<style scoped lang="less"></style>
